package com.call.utils;

import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class DesCipher {
	public String m_strKey;
	public Cipher m_objEncrypt;
	private Cipher m_objDecrypt;
	public DesCipher(String key) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException {
		m_strKey = key;
		m_objEncrypt = Cipher.getInstance("DES/CBC/PKCS5Padding");
		m_objDecrypt = Cipher.getInstance("DES/CBC/PKCS5Padding");
		// Create an 8-byte initialization vector
        byte[] iv = "12345678".getBytes();
        AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
		byte[] keyBytes = key.getBytes();
		byte[] newKeyBytes = new byte[8];
		
		for (int i = 0; i < 8; i++) {
			if (i < keyBytes.length)
				newKeyBytes[i] = keyBytes[i];
			else
				newKeyBytes[i] = 0;
		}
		SecretKeySpec desKey = new SecretKeySpec(newKeyBytes,"DES");
		m_objEncrypt.init(Cipher.ENCRYPT_MODE, desKey, paramSpec);
		m_objDecrypt.init(Cipher.DECRYPT_MODE, desKey, paramSpec);
	}
	public byte[] encrypt(String content) throws IllegalBlockSizeException, BadPaddingException {
		return (m_objEncrypt.doFinal(content.getBytes()));
	}
	public byte[] decrypt(byte[] code) throws IllegalBlockSizeException, BadPaddingException {
		return m_objDecrypt.doFinal(code);
	}
}
